package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebFilter("/*")
@Component
@Slf4j
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request1 = (HttpServletRequest) request;
        String requestURI = request1.getRequestURI();
        String[] loginUrls = {
                "/user/login",
                "/user/sendMsg",
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**" };
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String loginUrl : loginUrls) {
            boolean match = antPathMatcher.match(loginUrl, requestURI);
            if (match){
                chain.doFilter(request,response);
                return;
            }
        }
        HttpSession session = request1.getSession();
        Long employee = (Long) session.getAttribute("employee");
        User loginUser = (User) session.getAttribute("loginUser");
        if (employee != null || loginUser != null){
            //登录成功,向ThreadLocal存入当前用户的id
            if(employee!=null){
                UserHolder.setUserId(employee);
            }
            if(loginUser!=null){
                Long id = loginUser.getId();
                UserHolder.setUserId(id);
            }
//放行
            chain.doFilter(request,response);

//回去的代码，需要释放ThreadLocal中存储的用户id，防止内存溢出
            UserHolder.release();

        }else{
            HttpServletResponse response1 = (HttpServletResponse) response;
            R<Object> notlogin = R.error("NOTLOGIN");
            String string = JSON.toJSONString(notlogin);
            response1.getWriter().write(string);
        }

    }


}
